<template>
  <div>
    <div>
      <!-- 添加收款商品按钮 -->
      <div class="flex_between" style="margin-bottom: 10px">
        <div>
          <el-button v-if="!oId" type="info" @click="userVisible = true">
            添加用户
          </el-button>
          <el-button @click="prints()">打印结算单</el-button>
        </div>
        <el-button @click="$emit('send')">返回列表</el-button>
      </div>
      <!-- 手机号查询 -->
      <div v-if="!oId" class="flex_y_center" style="margin-bottom: 10px">
        <div>
          <span style="color: #fff">*</span>
          手机号：
        </div>
        <el-input
          v-model="tel"
          clearable
          placeholder="请输入搜索手机号"
          style="margin-right: 10px; width: 200px"
        />
        <el-button type="primary" @click="searchCus">搜索</el-button>
      </div>
      <!-- 选择客户，创建结算单 -->
      <div>
        <!-- 选择客户 -->
        <div v-if="!oId" style="display: flex">
          <!-- 选择家庭组 -->
          <div class="flex_y_center" style="margin-right: 15px">
            <div>
              <span>*</span>
              家庭组：
            </div>
            <el-select
              v-if="oId == 0"
              v-model="groupId"
              clearable
              filterable
              placeholder="请选择客户"
              remote
              :remote-method="getCus"
              style="width: 200px"
              @change="customerId = ''"
            >
              <el-option
                v-for="(item, index) of cusGroupList"
                :key="index"
                :label="item.group_name"
                :value="item.group_id"
              />
            </el-select>
          </div>
          <!-- 选择家长 -->
          <div class="flex_y_center" style="margin-right: 15px">
            <div>
              <span>*</span>
              家长：
            </div>
            <el-select
              v-if="oId == 0"
              v-model="customerId"
              clearable
              placeholder="请选择家长"
              style="width: 200px"
            >
              <el-option
                v-for="(item, index) of parentsList"
                :key="index"
                :label="item.cus_name + ' - ' + item.tel"
                :value="item.id"
              />
            </el-select>
          </div>
          <!-- 选择孩子 -->
          <div class="flex_y_center">
            <div>
              <span>*</span>
              孩子：
            </div>
            <el-select
              v-if="oId == 0"
              v-model="childId"
              clearable
              :disabled="!customerId"
              placeholder="请选择孩子"
              style="width: 200px"
            >
              <el-option
                v-for="(item, index) of childList"
                :key="index"
                :label="item.nick_name"
                :value="item.id"
              />
            </el-select>
          </div>
        </div>
        <div v-if="oId" class="flex_y_center">
          <div class="flex_y_center">
            <div>家庭组：</div>
            <div>{{ orderCusName }}</div>
          </div>
        </div>
      </div>
      <el-button style="margin: 10px 0" type="primary" @click="addBtn">
        添加商品
      </el-button>
      <!-- 展示用户添加要结算商品 -->
      <div>
        <el-table
          :data="settleGoodsInfo"
          default-expand-all
          row-key="attribute_id"
          :tree-props="{ children: 'json_fields' }"
        >
          >
          <el-table-column
            label="商品名"
            prop="goods_name"
            show-overflow-tooltip
          />
          <el-table-column label="规格" prop="attribute_name" />
          <el-table-column align="center" label="数量" width="200">
            <template slot-scope="scope">
              <el-input-number
                v-if="!scope.row.res_item_id"
                v-model="scope.row.goods_qty"
                :disabled="scope.row.gift_id"
                :min="1"
                size="mini"
                @change="changeNum(scope.row, scope.$index)"
              />
              <div v-else>{{ scope.row.goods_qty }}</div>
            </template>
          </el-table-column>
          <el-table-column label="单价(元)" prop="goods_price" />
          <el-table-column label="小计(元)" prop="total_amount" />
          <el-table-column label="优惠" prop="discount_amount" />
          <el-table-column label="运费" prop="express_fee" />
          <el-table-column label="状态">
            <template slot-scope="scope">
              {{ scope.row.status == 'wait' ? '待完成' : '已完成' }}
            </template>
          </el-table-column>
          <el-table-column align="left" label="操作">
            <template slot-scope="scope">
              <el-button
                v-if="!scope.row.res_item_id"
                type="danger"
                @click="delGoodsItem(scope.row)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 选择地址，分页 -->
      <div class="flex_between">
        <div>
          <div
            v-if="logisticsBool"
            class="flex_y_center"
            style="margin-left: 10px"
          >
            <el-radio-group
              v-model="delivery_method"
              style="margin-right: 10px"
              @change="chooseLogistics"
            >
              <el-radio label="express">送货上门</el-radio>
              <el-radio label="shop">到店自取</el-radio>
            </el-radio-group>
            <!-- 选择地址组件 -->
            <Choose-address
              v-if="delivery_method == 'express'"
              :address-info="addressList"
              :o-group-id="groupId"
              @send="finishAddress"
              @sendGet="getAddress"
            />
          </div>
        </div>
        <!-- 分页 -->
        <el-pagination
          :current-page.sync="page"
          layout="prev, pager, next, jumper"
          :total="total"
          @current-change="getDetail"
        />
      </div>
      <div
        style="display: flex; justify-content: space-between; margin-top: 20px"
      >
        <div>
          <el-tag type="danger">{{ couponInfo }}</el-tag>
        </div>
        <div>
          <div class="flex_between">
            <div>总计：</div>
            <div>￥{{ totalAmount }}</div>
          </div>
          <div v-if="couponInfo" class="flex_between" style="margin: 10px 0">
            <div>优惠：</div>
            <div style="margin-left: 20px">-￥{{ couponAmount }}</div>
          </div>
          <div class="flex_between">
            <div>应付金额：</div>
            <div style="margin-left: 20px">￥{{ receivePayment }}</div>
          </div>
        </div>
      </div>
      <!-- 功能 -->
      <div class="flex_between" style="margin: 15px 0">
        <!-- 挂/取单，门店活动 -->
        <div>
          <el-button @click="pendOrder">挂/取单</el-button>
          <el-button
            :disabled="settleGoodsInfo.length == 0"
            @click="handleClick"
          >
            门店活动
          </el-button>
          <el-button
            :disabled="settleGoodsInfo.length == 0"
            @click="saleDialog = true"
          >
            设置分销员
          </el-button>
        </div>
        <!-- 运费，结算金额 -->
        <div class="flex_y_center">
          <!-- 运费 -->
          <div
            v-if="delivery_method != '' && logisticsBool"
            class="flex_y_center"
          >
            <div>运费：</div>
            <!-- 展示运费 -->
            <div v-if="freightBool" class="flex_y_center">
              <div style="margin-right: 5px">{{ freight }}</div>
              <el-button
                v-if="delivery_method == 'express'"
                type="text"
                @click="freightBool = !freightBool"
              >
                修改
              </el-button>
            </div>
            <!-- 修改运费 -->
            <div v-else>
              <el-input
                v-model="freight"
                style="width: 60px; margin-right: 5px"
              />
              <el-button type="text" @click="changeFreight">完成</el-button>
            </div>
          </div>
          <!-- 结算金额 -->
          <div class="flex_y_center" style="margin-left: 10px">
            <!-- <div style="font-size: 23px; font-weight: 600">
              ￥{{ receivePayment }}
            </div>
            <div style="width: 10px"></div> -->
            <el-button round type="primary" @click="collection">
              收款￥{{ receivePayment }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加用户对话框 -->
    <el-dialog title="新增用户" :visible.sync="userVisible" width="30%">
      <AddUser :o-clear-user-form="clearUserForm" @send="closeUserDialog" />
    </el-dialog>

    <!-- 添加商品结算对话框 -->
    <el-dialog
      title="添加商品"
      :visible.sync="dialogGoodsVisible"
      :width="'70%'"
    >
      <!-- 添加需结算单的商品列表 -->
      <div>
        <!-- 商品数据 -->
        <div>
          <!-- 关键字搜索商品 -->
          <div>
            <el-input
              v-model="searchForm.goods_name"
              placeholder="请输入商品名"
              style="width: 25%"
            >
              <el-button slot="prepend" icon="el-icon-search" />
            </el-input>

            <el-select
              v-model="searchForm.method_id"
              clearable
              placeholder="请选择商品分组"
              style="margin: 0 5px"
              @focus="getGoodsMethod"
            >
              <el-option
                v-for="(item, index) of typeOptions"
                :key="index"
                :label="item.method_name"
                :value="item.id"
              />
            </el-select>
            <el-button icon="el-icon-search" type="primary" @click="getGoods">
              搜索
            </el-button>
          </div>
          <!-- 商品列表 -->
          <div
            v-loading="goodsLoad"
            class="grid_7_column"
            style="margin-top: 20px"
          >
            <div
              v-for="(item, index) of sourceGoodsInfo"
              v-show="sourceGoodsInfo.length != 0"
              :key="index"
              class="flex_dir_between goods_item"
              @click="addSettle(item)"
            >
              <div class="line_2">{{ item.goods_name }}</div>
              <div>类型：{{ item.goods_type }}</div>
              <div>规格名：{{ item.goods_attr_name }}</div>
              <div v-show="item.goods_type != '虚拟商品'">
                库存：{{ item.goods_attr_stock }}
              </div>
              <div style="height: 25px"></div>
              <div class="flex_between">
                <div></div>
                <div>￥{{ item.goods_attr_price }}</div>
              </div>
            </div>
          </div>
        </div>
        <!-- 无商品数据显示 -->
        <div
          v-show="sourceGoodsInfo.length == 0"
          class="flex_center"
          style="color: rgba(0, 0, 0, 0.5)"
        >
          暂无数据
        </div>
      </div>
      <!-- 右下角关闭按钮 -->
      <div slot="footer">
        <el-button type="danger" @click="dialogGoodsVisible = false">
          关 闭
        </el-button>
      </div>
    </el-dialog>

    <!-- 选择兑换商品对话框 -->
    <el-dialog title="选择兑换商品" :visible.sync="goodsVisible">
      <el-table
        ref="goods"
        border
        :data="goodsList"
        height="100%"
        stripe
        style="width: 100%"
        @select="chooseGoods"
      >
        <el-table-column type="selection" />
        <el-table-column label="商品名称" prop="goods_name" />
        <el-table-column label="价格" prop="price" />
      </el-table>
      <div slot="footer">
        <el-button type="primary" @click="submitGoods">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="订单信息"
      :visible.sync="printTestDialogVisible"
      width="50%"
    >
      <!-- 打印 -->
      <div id="printTests">
        <div class="UserPrint">
          <div>家庭组:{{ cusName.group_name }}</div>
          <div>家长:{{ cusName.customer_name }}</div>
          <div>孩子:{{ cusName.customer_member_name }}</div>
        </div>

        <table class="tftable" style="width: 98%">
          <thead>
            <tr>
              <td colspan="1">商品名称</td>
              <td colspan="1">规格名称</td>
              <td colspan="1">数量</td>
              <td colspan="1">单价(元)</td>
              <td colspan="1">优惠</td>
              <td colspan="1">运费</td>
            </tr>
          </thead>

          <tbody>
            <tr v-for="(items, k) in settleGoodsInfo" :key="k">
              <td>{{ items.goods_name }}</td>
              <td>{{ items.attribute_name }}</td>
              <td>{{ items.goods_qty }}</td>
              <td>{{ items.goods_price }}</td>
              <td>{{ items.discount_amount }}</td>
              <td>{{ items.express_fee }}</td>
            </tr>
          </tbody>
        </table>
        <div class="flex_y_center" style="margin-left: 10px">
          <div style="font-size: 23px; font-weight: 600">
            合计 ￥{{ receivePayment }}
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="printTestDialogVisible = false">取 消</el-button>
        <el-button
          v-permissions="{ permission: ['order-view:OrderList'] }"
          v-print="'#printTests'"
        >
          打印
        </el-button>
      </span>
    </el-dialog>

    <!-- 赠品，优惠券选择右侧抽屉 -->
    <el-drawer title="门店活动" :visible.sync="drawer">
      <div class="padding_10">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <!-- 赠品 -->
          <el-tab-pane label="赠品" name="first">
            <el-table
              ref="gift"
              :data="giftList"
              stripe
              style="width: 100%"
              tooltip-effect="dark"
              @select="chooseGift"
            >
              <el-table-column type="selection" />
              <el-table-column label="赠品名称" prop="gift_name" />
              <el-table-column label="商品名称" prop="goods_name" />
              <el-table-column label="规格名称" prop="attribute_name" />
            </el-table>
            <el-button
              style="margin-top: 10px"
              type="primary"
              @click="submitGift"
            >
              确认
            </el-button>
          </el-tab-pane>
          <!-- 优惠券 -->
          <el-tab-pane label="优惠卷" name="second">
            <div
              v-for="item in giveList"
              :key="item.id"
              class="coupon coupon-wave-left coupon-yellow"
              style="margin-left: 10%; cursor: pointer; font-size: 13px"
              @click="submitGive(item)"
            >
              <div class="coupon-info coupon-hole coupon-info-right-dashed">
                <!-- <div class="coupon-price">¥{{ item.coupon_amount }}</div> -->
                <div class="coupon-desc">{{ item.coupon_name }}</div>
                <div class="coupon-expiry-date">
                  有效期：{{ item.start_at + '—' + item.end_at }}
                </div>
                <div>
                  使用门槛：{{
                    parseInt(item.threshold_value)
                      ? item.threshold_value
                      : '无门槛'
                  }}
                </div>
                <div>优惠金额：{{ item.coupon_amount }}</div>
              </div>
              <div class="coupon-get coupon-get-already">立即使用</div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>

    <!-- 结算对话框 -->
    <el-dialog title="结算" :visible.sync="dialogVisible">
      <Settle
        :lump-sum="receivePayment"
        :o-stored-card="storedCard"
        :order-sn="order_sn"
        @close="dialogVisible = false"
        @send="settleSucess"
      />
    </el-dialog>

    <!-- 订单完成对话框 -->
    <el-dialog
      :before-close="demo"
      title="订单完成"
      :visible.sync="statusVisible"
    >
      <div>
        <el-result
          icon="success"
          sub-title="支付成功, 点击下方按钮返回"
          title="支付成功"
        >
          <template slot="extra">
            <el-button type="primary" @click="$emit('send')">关闭</el-button>
          </template>
        </el-result>
      </div>
    </el-dialog>

    <!-- 选择分销员对话框 -->
    <el-dialog title="选择分销员" :visible.sync="saleDialog">
      <ChooseSale @send="finishSale" />
    </el-dialog>
  </div>
</template>

<script>
  import { getCusGroup } from '@/api/gustomerGroup'
  import { payHandle } from '@/api/order'
  import { cusGroupDetail } from '@/api/level'
  import { getPrepaidList } from '@/api/storedValue'
  import { getCommodityType } from '@/api/commodity'
  import {
    getGiftList,
    getCouponList,
    choiceCoupon,
    choiceGift,
    getGoodsList,
  } from '@/api/public'
  import {
    addComsume,
    insertConsume,
    moveComsume,
    changeComsume,
    getConsumeDetail,
    setDeliveryMethod,
    editExpressFee,
  } from '@/api/toll'

  export default {
    components: {
      ChooseAddress: () => import('./components/chooseaddress.vue'), // 选择地址
      Settle: () => import('./components/settle.vue'), // 结算
      AddUser: () => import('./components/adduser.vue'), // 添加用户
      ChooseSale: () => import('./components/choosesale.vue'), // 选择
    },
    props: {
      oId: {
        type: Number,
        default: 0,
      },
      oCusId: {
        type: Number,
        default: 0,
      },
    },
    data() {
      return {
        giftList: [], // 赠品表格
        giveList: [], // 优惠卷数据
        goodsList: [], // 存放当前选择兑换券的列表
        couponId: '', // 选中优惠券id
        giftId: '', // 选中赠品id
        goodsId: '', // 选择兑换商品的id
        goodsVisible: false, // 兑换商品dialog
        statusVisible: false, // 订单完成dialog
        userVisible: false, // 新增用户dialog
        clearUserForm: '',
        saleDialog: false, // 选择分销员dialog
        userIds: [], // 存放选择的员工id

        tel: '', // 手机号搜索用户关键字
        cusGroupList: [], // 存放客户，家庭组列表
        parentsList: [], // 当前选择家庭组下的成员列表
        childList: [], // 当前选择家庭组下孩子列表
        childId: '', // 孩子id
        customerId: '', // 存放用户选择的客户id
        groupId: '', // 客户id，用于获取该客户的收货地址
        id: '', // 存放创建完收费单的id
        cusName: {
          group_name: '',
          customer_name: '',
          customer_member_name: '',
        },

        dialogGoodsVisible: false, // 控制添加商品对话框的显示和隐藏
        typeOptions: [], // 存放商品分组
        // 关键字搜索
        searchForm: {
          goods_type: 'all',
          goods_name: '',
          method_id: '',
        },
        goodsLoad: false,
        sourceGoodsInfo: [], // 源商品数据
        settleGoodsInfo: [], // 结算商品数据

        addressList: [], // 存放该选择角色的地址

        addressForm: {}, // 作为创建订单时的参数
        delivery_method: '', // 选择发货还是到店自取

        page: 1,
        total: 10, // 分页页数

        drawer: false, // 控制右侧抽屉打开关闭
        couponInfo: '', // 存放该单的优惠信息
        couponAmount: '0', // 优惠金额
        totalAmount: '0', // 未使用优惠券金额
        activeName: 'first',
        receivePayment: '0', // 存放订单总金额
        freight: 0, // 存放订单运费
        freightBool: true, // 控制修改运费输入框显示隐藏
        dialogVisible: false, // 控制结算对话框的显示和隐藏
        storedCard: [], // 存放当前用户下的储值卡
        order_sn: '', // 存放后端返回的订单号
        printTestDialogVisible: false, //打印
      }
    },
    computed: {
      // 判断是否显示选择收货地址
      logisticsBool() {
        let bool = false
        // 检索实物商品类型
        for (let item of this.settleGoodsInfo) {
          // 判断如果出现实物商品，那么显示选择收货地址
          if (item.type_code == 'entity') {
            bool = true
          } else {
            bool = false
          }
        }
        return bool
      },
      // 当前结算用户
      orderCusName() {
        return (
          this.cusName.group_name +
          ' - ' +
          this.cusName.customer_name +
          ' - ' +
          this.cusName.customer_member_name
        )
      },
    },
    watch: {
      // 监视用户选择家庭组后的状态，只要用户选择客户信息，那么都会执行这个方法
      groupId(newValue) {
        this.id = ''
        // 判断是否为空
        if (newValue != '') {
          // 即将选择的家庭组中的家长，孩子信息筛选出来
          for (let item of this.cusGroupList) {
            if (item.group_id == this.groupId) {
              this.parentsList = item.user
              this.childList = item.child
              break
            }
          }
        } else {
          this.customerId = ''
          this.tel = ''
        }
      },
      // 删除孩子id的值
      customerId(newValue) {
        if (!newValue) {
          this.childId = ''
        }
      },
      // 监听用户选择的物流方式，并执行获取地址或清空
      delivery_method(newValue) {
        if (newValue == 'express') {
          this.getAddress()
        } else {
          this.addressForm.delivery_method = 'shop'
          this.addressList = []
          this.addressForm = {}
          this.freight = 0
        }
      },
      // 如果结算对话框关闭，那么返回挂单列表界面
      dialogVisible(newValue) {
        if (!newValue) {
          this.$emit('send')
        }
      },
      // 用于告诉新增用户对话框是显示还是隐藏
      userVisible(newValue) {
        this.clearUserForm = !newValue
      },
    },
    mounted() {
      this.getGoods()
      // 判断是否为编辑
      if (this.oId) {
        const loading = this.$loading({
          lock: true,
          target: '.el-table__empty-block',
        })
        this.getDetail(loading)
      } else {
        this.getCus()
      }
    },
    methods: {
      demo() {
        this.$message.warning('请点击下方返回按钮')
      },
      // 获取家庭组，用户(家长，孩子)
      getCus(keyWord) {
        const data = {
          group_name: keyWord,
        }
        getCusGroup(data).then((res) => {
          this.cusGroupList = res.data
        })
      },
      // 手机号模糊搜索
      searchCus() {
        const data = {
          tel: this.tel,
        }
        getCusGroup(data).then((res) => {
          if (res.data.length == 0) this.$message.warning('未搜索到用户')
          else {
            this.groupId = res.data[0].group_id
            this.customerId = res.data[0].user[0].id
            this.childId = res.data[0].child[0].id
          }
        })
      },
      // 获取添加商品结算单列表详情，并检索是否有实物商品
      getDetail(loading) {
        const params = {
          id: this.oId || this.id,
          page: this.page,
        }
        // 添加完结算商品后，调用结算详情获取后端保存数据
        getConsumeDetail(params).then((res) => {
          this.settleGoodsInfo = res.data.item
          this.groupId = res.data.group_id

          this.cusName.group_name = res.data.group_name
          this.cusName.customer_name = res.data.customer_name
          this.cusName.customer_member_name = res.data.customer_member_name

          if (res.data.customer_coupon_id) {
            this.totalAmount = res.data.original_amount
            this.couponInfo = `${res.data.coupon_type}，已优惠￥${res.data.coupon_amount}元`
          }

          this.receivePayment = res.data.total_amount
          if (loading) loading.close()
        })
      },
      // 获取商品
      getGoods() {
        this.goodsLoad = true
        getGoodsList(this.searchForm).then((res) => {
          this.sourceGoodsInfo = []
          for (let item of res.data) {
            if (item.type_code != 'curriculum') {
              switch (item.type_code) {
                case 'entity':
                  item.goods_type = '实物商品'
                  break
                case 'virtual':
                  item.goods_type = '虚拟商品'
                  break
                case 'card':
                  item.goods_type = '电子卡卷'
                  break
                case 'service':
                  item.goods_type = '定金服务'
                  break
                case 'report':
                  item.goods_type = '体验报告'
                  break
                case 'therapy':
                  item.goods_type = '辅助治疗'
                  break
                case 'drugs':
                  item.goods_type = '药品'
                  break
                case 'advice':
                  item.goods_type = '处方'
                  break
              }
              this.sourceGoodsInfo.push(item)
            }
          }
          this.goodsLoad = false
        })
      },
      // 获取商品分组
      getGoodsMethod() {
        if (this.typeOptions.length == 0) {
          getCommodityType().then((res) => {
            this.typeOptions = res.data
          })
        }
      },
      // 判断当前是否可以选择商品
      addBtn() {
        if (this.oId || this.id) {
          this.dialogGoodsVisible = true // 打开选择商品对话框
        } else {
          if (this.childId) {
            // 添加用户结算单
            const params = {
              group_id: this.groupId,
              res_customer_id: this.customerId, // 使用用户当前选择最新的客户id
              app_customer_id: this.childId,
            }
            addComsume(params).then((res) => {
              if (res.data.length == 0) {
                this.$message.warning(res.message)
              } else {
                this.id = res.data.id
                this.dialogGoodsVisible = true // 打开选择商品对话框
                this.getDetail()
              }
            })
          } else {
            this.$message.error('请先选择客户')
          }
        }
      },
      // 选择商品添加到结算列表
      addSettle(item) {
        const loading = this.$loading({
          lock: true,
          target:
            this.settleGoodsInfo.length == 0
              ? '.el-table__empty-block'
              : '.el-table__body',
        })
        const params = {
          id: this.oId || '',
          type_id: item.type_id,
          customer_id: this.customerId || this.oCusId, // 用户id
          goods_id: item.goods_id, // 商品id
          goods_name: item.goods_name, // 商品名称
          attribute_id: item.goods_attr_id, // 规格id
          attribute_name: item.goods_attr_name, // 规格名称
          goods_price: item.goods_attr_price, // 商品单价
          goods_qty: 1, // 商品数量
          delivery_method: item.delivery_method, // 商品配送方式
          discount_amount: 0, // 商品优惠价格，(暂时传0)
        }
        insertConsume(params).then((res) => {
          this.receivePayment = res.data.tatal_price
          this.$message.success(item.goods_name + '商品添加成功')
          this.getDetail(loading)
        })
      },
      // 改变结算商品数量
      changeNum(item, index) {
        const loading = this.$loading({
          lock: true,
          target:
            this.settleGoodsInfo.length == 0
              ? '.el-table__empty-block'
              : '.el-table__body',
        })
        const parmas = {
          customer_id: this.customerId || this.oCusId, // 客户id
          consume_id: item.id,
          num: item.goods_qty, // 修改的数量
        }
        changeComsume(parmas).then((res) => {
          this.settleGoodsInfo[index].total_amount =
            res.data.tatal_amount + '.00'
          this.receivePayment = res.data.tatal_price
          this.getDetail(loading)
        })
      },
      // 移除结算商品项
      delGoodsItem(item) {
        this.$confirm('确定将' + item.goods_name + '移除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            target:
              this.settleGoodsInfo.length == 0
                ? '.el-table__empty-block'
                : '.el-table__body',
          })
          const params = {
            consume_id: item.id, // 列表id
            customer_id: this.customerId || this.oCusId, // 子id
          }
          moveComsume(params).then(() => {
            for (let key of this.goodsList) {
              if (item.goods_id == key.goods_id) {
                key.bool = false
              }
            }
            // 点击确定
            this.$message.success(item.goods_name + '已移除!')
            this.getDetail(loading)
          })
        })
      },

      // 关闭新增用户对话框，判断是否要调用接口重新获取客户组
      closeUserDialog(e) {
        this.userVisible = false
        if (typeof e == 'object') {
          this.tel = ''
          getCusGroup().then((res) => {
            this.cusGroupList = res.data
            // 即将选择的家庭组中的家长，孩子信息筛选出来
            for (let item of this.cusGroupList) {
              if (item.group_id == e.groupId) {
                this.parentsList = item.user
                this.childList = item.child
                break
              }
            }

            this.groupId = e.groupId
            this.customerId = e.customerId
            this.childId = e.childId
          })
        }
      },

      // 选择物流方式，获取运费
      chooseLogistics() {
        const params = {
          id: this.oId || this.id, // 结算单id
          delivery_method: this.delivery_method, // 物流方式
        }
        setDeliveryMethod(params).then((res) => {
          this.freight = res.data.total_express_fee
          this.getDetail()
        })
      },
      // 修改运费
      changeFreight() {
        const params = {
          id: this.oId || this.id, // 结算单id
          express_fee: this.freight, // 修改的运费
        }
        editExpressFee(params).then((res) => {
          this.freight = res.data.total_express_fee
          this.freightBool = !this.freightBool
          this.getDetail()
        })
      },
      // 获取对应客户地址
      getAddress() {
        const params = {
          group_id: this.groupId,
        }
        cusGroupDetail(params).then((res) => {
          this.addressList = res.data.address
        })
      },
      // 选择完成地址
      finishAddress(data) {
        this.addressForm = data
      },
      // 挂单
      pendOrder() {
        this.$confirm('确定要将该单挂取吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.$emit('send')
        })
      },

      // 点击标签页
      handleClick() {
        this.drawer = true
        this.activeName == 'first' ? this.getDiscount() : this.getGive()
      },
      // 获取赠品
      getDiscount() {
        if (this.giftList.length == 0) {
          this.giftList = []
          const data = {
            customer_id: this.customerId || this.oCusId,
          }
          getGiftList(data).then((res) => {
            this.giftList = res.data
          })
        }
      },
      // 选择赠品
      chooseGift(selection, row) {
        this.$refs.gift.clearSelection()
        if (selection.length === 0) {
          // 判断selection是否有值存在
          return
        }
        if (row) {
          this.giftId = row.id
          this.$refs.gift.toggleRowSelection(row, true)
        }
      },
      // 提交赠品
      submitGift() {
        const loading = this.$loading({
          lock: true,
          target: '.el-table__body',
        })
        const data = {
          customer_id: this.customerId || this.oCusId,
          gift_id: this.giftId,
        }
        choiceGift(data).then(() => {
          this.drawer = false
          this.getDetail(loading)
        })
      },
      // 获取优惠券
      getGive() {
        const data = {
          customer_id: this.customerId || this.oCusId,
        }
        getCouponList(data).then((e) => {
          this.giveList = []
          e.data.forEach((j) => {
            if (j.is_usable == 'Y') {
              this.giveList.push(j)
            }
          })
        })
      },
      // 选中优惠券，判断优惠券类型，如果是兑换券打开兑换券对话框
      submitGive(e) {
        if (e.coupon_type == 'goods') {
          this.goodsList = []
          this.couponId = e.id
          // 将用户按当前选择的兑换券可兑换商品和选择商品做比较，如果相同那么添加到指定数组
          if (e.coupon_goods) {
            this.goodsVisible = true
            for (let item of this.settleGoodsInfo) {
              for (let itemChild of e.coupon_goods) {
                if (item.goods_name == itemChild.goods_name) {
                  this.goodsList.push(itemChild)
                }
              }
            }
          } else {
            this.$message.error('当前选择优惠券，没有可兑换商品')
          }
        } else {
          const loading = this.$loading({
            lock: true,
            target: '.el-table__body',
          })
          const data = {
            customer_id: this.customerId || this.oCusId,
            coupon_id: e.id,
          }
          choiceCoupon(data).then(() => {
            this.getDetail(loading)
            this.drawer = false
          })
        }
      },
      // 选择兑换商品
      chooseGoods(selection, row) {
        this.$refs.goods.clearSelection()
        if (selection.length === 0) {
          // 判断selection是否有值存在
          return
        }
        if (row) {
          this.goodsId = row.attribute_id
          this.$refs.goods.toggleRowSelection(row, true)
        }
      },
      // 提交选择的兑换商品
      submitGoods() {
        const data = {
          customer_id: this.customerId || this.oCusId,
          coupon_id: this.couponId,
          attribute_id: this.goodsId,
        }
        choiceCoupon(data).then(() => {
          this.getDetail()
          this.drawer = false // 关闭抽屉
          this.goodsVisible = false // 关闭选择商品对话框
        })
      },

      // 赋值
      finishSale(userList) {
        this.userIds = userList
        this.saleDialog = false
      },

      // 检查用户选择添加了实物商品到结算列表后，是否有选择送货方式，送货地址
      searchAddress() {
        // 如果 logisticsBool 为false，结算商品列表中无实物商品时
        if (this.logisticsBool == false) {
          return false
        } else {
          // 结算商品列表中有实物商品时
          // 如果delivery_method为空的话
          if (this.delivery_method == '') {
            this.$message.warning('请选择物流方式')
            return true
          } else {
            // delivery_method中有值时
            // 如果 delivery_method 为N
            if (this.delivery_method == 'shop') {
              return false
            } else {
              if (JSON.stringify(this.addressForm) == '{}') {
                this.$message.error('请选择送货地址')
                return true
              } else {
                return false
              }
            }
          }
        }
      },
      // 创建订单前，检索表单
      collection() {
        // false为通过，true为未通过
        if (!this.searchAddress()) {
          if (this.settleGoodsInfo.length == 0) {
            this.$message.warning('请先添加商品')
          } else {
            for (let item of this.settleGoodsInfo) {
              if (item.status == 'wait') {
                this.$message.warning(
                  '当前待结算商品列表中，存在辅助治疗或检验检测的待完成商品，请处理后在进行结算'
                )
                return
              }
            }
            if (this.receivePayment == 0) {
              this.$confirm(
                '当前订单价格 ' + this.receivePayment + ' 元, 是否提交订单',
                '提示',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                }
              ).then(() => {
                this.createdHandle()
              })
            } else {
              this.createdHandle()
            }
          }
        }
      },
      // 创建订单
      createdHandle() {
        const params = {
          prepaid_type: 'prepaid',
        }
        getPrepaidList(params).then((res) => {
          this.storedCard = res.data
          let params = this.addressForm
          params.customer_id = this.customerId || this.oCusId
          params.channel_type = 'order'
          params.user_ids = this.userIds.length == 0 ? '' : this.userIds

          // 创建订单
          payHandle(params)
            .then((res) => {
              if (this.receivePayment == 0) {
                this.statusVisible = true
              } else {
                this.order_sn = res.data.order_sn
                this.receivePayment = res.data.ord_amount
                this.dialogVisible = true
              }
            })
            .catch(() => this.$message.error('订单创建失败'))
        })
      },
      // 订单结束
      settleSucess() {
        this.dialogVisible = false // 关闭结算对话框
        this.statusVisible = true // 打开结算完成对话框
      },
      prints() {
        // 打印
        this.printTestDialogVisible = true
      },
    },
  }
</script>

<style scoped>
  .right {
    float: right;
  }
  .flex_between {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .flex_center {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .flex_dir_between {
    display: flex;
    justify-content: space-between;
    flex-direction: column;
  }
  .grid_7_column {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    grid-gap: 15px;
  }
  .grid_3_column {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 15px;
  }
  .line_2 {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
  span {
    color: red;
  }

  .goods_item {
    background-color: lightblue;
    padding: 10px;
    cursor: pointer;
    transition: 0.5s;
  }
  .mark_payment {
    border: 1px solid rgba(0, 0, 0, 0.1);
    padding: 10px 0;
    display: flex;
    align-items: center;
  }
  .goods_item,
  .mark_payment {
    transition: 0.3s;
  }
  .goods_item:hover,
  .mark_payment:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
  }

  /* 优惠券 */
  .coupon {
    display: inline-flex;
    color: white;
    position: relative;
    padding-left: 0.5rem;
    padding-right: 0.5rem;
    /* margin: 1rem; */
    /** 弧度得用rem来计数，不能用%号，因为%是用来计数高度和宽度的 */
    border-top-right-radius: 0.3rem;
    border-bottom-right-radius: 0.3rem;
    overflow: hidden;
  }
  .coupon-yellow {
    background-color: #f39b00;
  }
  .coupon-yellow-gradient {
    background-image: linear-gradient(150deg, #f39b00 50%, #f39b00d8 50%);
  }
  .coupon-red-gradient {
    background-image: linear-gradient(150deg, #d24161 50%, #d24161d8 50%);
  }
  .coupon-green-gradient {
    background-image: linear-gradient(150deg, #7eab1e 50%, #7eab1ed8 50%);
  }
  .coupon-blue-gradient {
    background-image: linear-gradient(150deg, #50add3 50%, #50add3d8 50%);
  }
  /** 左边框波浪 **/
  .coupon-wave-left::before,
  .coupon-wave-right::after {
    content: '';
    position: absolute;
    top: 0;
    height: 100%;
    width: 14px;
    background-image: radial-gradient(white 0, white 4px, transparent 4px);
    /** 若只设置为r（半径）的两倍(直径)，则半圆之间没有类似堤岸的间隔 */
    background-size: 14px 14px;
    background-position: 0 2px;
    background-repeat: repeat-y;
    z-index: 1;
  }
  .coupon-wave-left::before {
    left: -7px;
  }
  .coupon-wave-right::after {
    right: -7px;
  }
  .coupon-info {
    width: 100%;
    padding: 1rem;
    position: relative;
    /* min-width: 15rem; */
  }
  .coupon-info-right-dashed {
    border-right: 2px dashed white;
  }
  .coupon-info-right-solid {
    border-right: 2px solid white;
  }
  /** 使用两个边框为圆角的白色div制造半圆缺角，有个缺点是这个缺角必须与背景色相同（clip-path不好使用） **/
  .coupon-hole::before,
  .coupon-hole::after {
    content: '';
    width: 1rem;
    height: 1rem;
    background-color: white;
    border-radius: 50%;
    position: absolute;
    right: -0.5rem;
  }
  .coupon-info::before {
    top: -0.5rem;
  }
  .coupon-info::after {
    bottom: -0.5rem;
  }
  .coupon-info > div {
    margin-bottom: 0.2rem;
  }
  .coupon-price {
    font-size: 250%;
    font-weight: bold;
  }
  .coupon-price > span {
    font-size: 40%;
    margin-left: 0.5rem;
    font-weight: normal;
  }
  .coupon-get {
    padding: 1rem;
    /** 这里使用flex是为了让文字居中 */
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    min-width: 6rem;
    /* width: fit-content; */
    position: relative;
  }
  .coupon-get > .coupon-desc {
    font-size: 150%;
    margin-bottom: 0.5rem;
    font-weight: bold;
  }
  table.tftable,
  table.table-count {
    font-size: 12px;
    color: #333333;
    width: 100%;
    border-width: 1px;
    border-collapse: collapse;
  }

  table.table-count th,
  table.table-count td {
    font-weight: 400;
    font-style: normal;
    font-size: 12px;
    border-width: 1px;
    border-style: solid;
    border-color: #e4e4e4;
    text-align: center;
  }

  table.tftable th,
  table.tftable td {
    font-weight: 400;
    font-style: normal;
    font-size: 12px;
    border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #e4e4e4;
    text-align: left;
    text-align: center;
  }

  .tftable {
    margin-left: 1%;
    margin-bottom: 10px;
    margin-top: 10px;
  }
  table.tftable tr:hover {
    /* background: #c3ecff; */
  }
  .tftable > thead > tr:hover {
    background: white;
  }
  .UserPrint {
    padding-top: 20px;
    display: flex;
    justify-content: space-around;
    border-bottom: 1px solid;
    padding-bottom: 10px;
  }
</style>
